<template>
    <div class="main-page">
        <div class="amplifier-panel-container" 
            @touchstart="touchStart" 
            @touchmove="touchMove" 
            @touchend="touchEnd"
            @mousedown="mouseDown" 
            @contextmenu.prevent>
            <div class="amplifier-panels" :style="panelsStyle">
                <SoloistAmplifier ref="soloistAmplifier" :style="amplifierStyle" />
                <Eddie51Amplifier ref="eddie51Amplifier" :style="amplifierStyle" />
                <DizzlVHAmplifier ref="dizzlVHAmplifier" :style="amplifierStyle" />
            </div>
        </div>
        <div class="effects-panel-container">
            <EffectsPanel />
        </div>
    </div>
</template>

<script>
import { 
    defineComponent, 
    ref, 
    computed, 
    onMounted, 
    onUnmounted, 
    watch, 
    nextTick,
    shallowRef,
    defineAsyncComponent
} from 'vue';

// 异步加载组件
const Eddie51Amplifier = defineAsyncComponent(() => import('./Eddie51Amplifier.vue'));
const DizzlVHAmplifier = defineAsyncComponent(() => import('./DizzlVHAmplifier.vue'));
const EffectsPanel = defineAsyncComponent(() => import('./EffectsPanel.vue'));
const SoloistAmplifier = defineAsyncComponent(() => import('./SoloistAmplifier.vue'));

// 节流函数
const throttle = (fn, delay) => {
    let lastCall = 0;
    return (...args) => {
        const now = Date.now();
        if (now - lastCall >= delay) {
            fn(...args);
            lastCall = now;
        }
    };
};

export default defineComponent({
    name: 'Vstomp',
    components: {
        SoloistAmplifier,
        Eddie51Amplifier,
        DizzlVHAmplifier,
        EffectsPanel
    },
    setup() {
        // 使用 shallowRef 优化大数组的响应式
        const amplifierPanels = shallowRef([
            { id: 1, type: 'SoloistAmplifier' },
            { id: 2, type: 'Eddie51Amplifier' },
            { id: 3, type: 'DizzlVHAmplifier' }
        ]);

        const currentPanelIndex = ref(1);
        const currentTranslateX = ref(-1920);        
        const targetTranslateX = ref(-1920);
        const touchPoints = ref(0);
        const amplifierTypes = ['SoloistAmplifier', 'Eddie51Amplifier', 'DizzlVHAmplifier'];

        // 组件引用
        const soloistAmplifierRef = ref(null);
        const eddie51AmplifierRef = ref(null);
        const dizzlVHAmplifierRef = ref(null);

        // 触摸和动画相关状态
        let startX = 0;
        let isRightClick = false;
        let touchMoveRAF = null;
        let switchTimeout = null;

        // 使用 ResizeObserver 监听窗口大小变化
        const windowWidth = ref(window.innerWidth);
        const resizeObserver = new ResizeObserver(throttle(() => {
            windowWidth.value = window.innerWidth;
            targetTranslateX.value = -currentPanelIndex.value * windowWidth.value;
            updateTranslateX();
        }, 16));

        // 监听放大器切换
        watch(currentPanelIndex, async (newIndex) => {
            if (switchTimeout) {
                clearTimeout(switchTimeout);
            }

            switchTimeout = setTimeout(async () => {
                const newAmplifierType = amplifierTypes[newIndex];
                try {
                    const result = await window.electronAPI.switchAmplifier(newAmplifierType);
                    if (result.success) {
                        await nextTick();
                        
                        let currentAmplifier;
                        switch (newAmplifierType) {
                            case 'SoloistAmplifier':
                                currentAmplifier = soloistAmplifierRef.value;
                                break;
                            case 'Eddie51Amplifier':
                                currentAmplifier = eddie51AmplifierRef.value;
                                break;
                            case 'DizzlVHAmplifier':
                                currentAmplifier = dizzlVHAmplifierRef.value;
                                break;
                        }

                        if (currentAmplifier?.getCurrentState) {
                            const state = currentAmplifier.getCurrentState();
                            await Promise.all(
                                Object.entries(state).map(async ([label, value]) => {
                                    if (label === 'switchState') {
                                        await window.electronAPI.setProcessorBypass(result.processorId, !value);
                                    } else {
                                        await window.electronAPI.sendKnobValue(label, value);
                                    }
                                })
                            );
                        }
                    }
                } catch (error) {
                    console.error('Error switching amplifier:', error);
                }
            }, 100);
        }, { flush: 'post' });

        // 计算样式
        const panelsStyle = computed(() => ({
            transform: `translate3d(${currentTranslateX.value}px, 0, 0)`,
            willChange: 'transform'
        }));

        const amplifierStyle = computed(() => ({
            width: '100vw',
            flexShrink: 0,
            willChange: 'transform'
        }));

        // 动画处理
        const updateTranslateX = () => {
            const animate = () => {
                const diff = targetTranslateX.value - currentTranslateX.value;
                if (Math.abs(diff) > 1) {
                    currentTranslateX.value += diff * 0.3;
                    requestAnimationFrame(animate);
                } else {
                    currentTranslateX.value = targetTranslateX.value;
                }
            };
            requestAnimationFrame(animate);
        };

        // 触摸事件处理
        const touchStart = (event) => {
            touchPoints.value = event.touches.length;
            if (touchPoints.value === 2) {
                startX = event.touches[0].clientX;
            }
        };

        const handleTouchMove = (event) => {
            if (touchPoints.value !== 2 || startX === 0) return;
            const currentX = event.touches[0].clientX;
            const diff = currentX - startX;
            const newTranslateX = -currentPanelIndex.value * windowWidth.value + diff;

            if (newTranslateX <= 0 && newTranslateX >= -(amplifierPanels.value.length - 1) * windowWidth.value) {
                targetTranslateX.value = newTranslateX;
                updateTranslateX();
            }
        };

        const touchMove = (event) => {
            if (touchMoveRAF) {
                cancelAnimationFrame(touchMoveRAF);
            }
            touchMoveRAF = requestAnimationFrame(() => handleTouchMove(event));
        };

        const touchEnd = (event) => {
            if (touchPoints.value !== 2 || startX === 0) {
                touchPoints.value = 0;
                return;
            }

            const endX = event.changedTouches[0].clientX;
            const difference = endX - startX;

            if (Math.abs(difference) > windowWidth.value * 0.25) {
                if (difference > 0 && currentPanelIndex.value > 0) {
                    currentPanelIndex.value--;
                } else if (difference < 0 && currentPanelIndex.value < amplifierPanels.value.length - 1) {
                    currentPanelIndex.value++;
                }
            }

            targetTranslateX.value = -currentPanelIndex.value * windowWidth.value;
            updateTranslateX();
            startX = 0;
            touchPoints.value = 0;
        };

        // 鼠标事件处理
        const mouseDown = (event) => {
            if (event.button === 2) {
                event.preventDefault();
                isRightClick = true;
                startX = event.clientX;
                window.addEventListener('mousemove', mouseMove);
                window.addEventListener('mouseup', mouseUp);
            }
        };

        const mouseMove = throttle((event) => {
            if (!isRightClick) return;
            const currentX = event.clientX;
            const diff = currentX - startX;
            const newTranslateX = -currentPanelIndex.value * windowWidth.value + diff;

            if (newTranslateX <= 0 && newTranslateX >= -(amplifierPanels.value.length - 1) * windowWidth.value) {
                targetTranslateX.value = newTranslateX;
                updateTranslateX();
            }
        }, 16);

        const mouseUp = (event) => {
            if (!isRightClick) return;
            const endX = event.clientX;
            const difference = endX - startX;

            if (Math.abs(difference) > windowWidth.value * 0.25) {
                if (difference > 0 && currentPanelIndex.value > 0) {
                    currentPanelIndex.value--;
                } else if (difference < 0 && currentPanelIndex.value < amplifierPanels.value.length - 1) {
                    currentPanelIndex.value++;
                }
            }

            targetTranslateX.value = -currentPanelIndex.value * windowWidth.value;
            updateTranslateX();
            cleanupMouseEvents();
        };

        const cleanupMouseEvents = () => {
            isRightClick = false;
            startX = 0;
            window.removeEventListener('mousemove', mouseMove);
            window.removeEventListener('mouseup', mouseUp);
        };

        // 生命周期钩子
        onMounted(() => {
            window.addEventListener('blur', cleanupMouseEvents);
            resizeObserver.observe(document.body);
        });

        onUnmounted(() => {
            cleanupMouseEvents();
            window.removeEventListener('blur', cleanupMouseEvents);
            resizeObserver.disconnect();
            
            if (touchMoveRAF) {
                cancelAnimationFrame(touchMoveRAF);
            }
            if (switchTimeout) {
                clearTimeout(switchTimeout);
            }
        });

        return {
            amplifierPanels,
            currentPanelIndex,
            currentTranslateX,
            touchPoints,
            panelsStyle,
            amplifierStyle,
            touchStart,
            touchMove,
            touchEnd,
            mouseDown,
            soloistAmplifier: soloistAmplifierRef,
            eddie51Amplifier: eddie51AmplifierRef,
            dizzlVHAmplifier: dizzlVHAmplifierRef,
        };
    }
});
</script>

<style>
.main-page {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    position: relative;
    transform: translateZ(0);
}

.amplifier-panel-container {
    flex: 1;
    overflow: hidden;
    position: relative;
    touch-action: pan-y;
    transform: translateZ(0);
}

.amplifier-panels {
    display: flex;
    width: 100%;
    height: 100%;
    transform-style: preserve-3d;
    will-change: transform;
    backface-visibility: hidden;
}

.effects-panel-container {
    width: 100%;
    height: auto;
    min-height: 200px;
    max-height: 40%;
    transform: translateZ(0);
}
</style>